package com.shortlink.gateway.filter;

import com.shortlink.common.base.Result;
import com.shortlink.common.base.Results;
import com.shortlink.common.constant.HeaderConstant;
import com.shortlink.common.exception.ClientException;
import com.shortlink.common.ratelimiter.RateLimiter;
import com.shortlink.gateway.util.FilterUtils;
import jakarta.annotation.Resource;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;

import static com.shortlink.common.base.errcode.BaseErrorCode.FLOW_LIMIT_ERROR;
import static com.shortlink.gateway.constant.RateLimiterConstant.USER_RATE_LIMITER_NAME;

/**
 * 用户操作流量风控过滤器
 *
 * @author wp
 */
@Component
public class UserFlowRiskControlGatewayFilterFactory extends AbstractGatewayFilterFactory<Object> {
    @Resource
    private RateLimiter rateLimiter;

    @Override
    public GatewayFilter apply(Object config) {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            String userId = request.getHeaders().getFirst(HeaderConstant.USER_ID);
            boolean acquire = rateLimiter.tryAcquire(String.format(USER_RATE_LIMITER_NAME, userId));
            if (!acquire) {
                //拒绝请求
                Result<Void> result = Results.failure(new ClientException(FLOW_LIMIT_ERROR));
                return FilterUtils.returnJson(exchange, result);
            }
            return chain.filter(exchange);
        };
    }
}
